<script>
import { api } from '@/api';
import { mapStores } from 'pinia'
import { useAppStore } from '@/stores/app';
import { Button, Field, Form, Toast } from 'vant';

export default {
  components: {
    Button,
    Form,
    Field
  },
  computed: {
    ...mapStores(useAppStore)
  },
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    setUsername(username) {
      this.username = username
    },
    async onSubmit(data) {
      const loading = Toast.loading({ message: '登录中...' })

      const res = await api.login({
        userName: data.username,
        passwd: data.password
      })

      loading.clear()

      if (res.success) {
        this.appStore.setUserInfo({
          uid: res.data.uid,
          username: res.data.user_name,
          nickname: res.data.nick_name,
          avatar: `/${res.data.avatar_url}`,
          mobile: res.data.mobile ?? '',
          invitationCode: res.data.invitation_code
        })
        this.appStore.setToken(data.username)
        this.$router.push({ name: 'Home' })
        Toast.success({ message: '登录成功' })
      } else {
        Toast.fail({ message: res.msg ?? '登录失败' })
      }
    }
  }
}
</script>

<template>
  <Form @submit="onSubmit">
    <Field 
      v-model="username"
      name="username"
      placeholder="请输入用户名"
      size="large"
      autocomplete="username"
      :rules="[{ required: true, message: '请填写用户名' }]"
    >
      <template #left-icon>
        <div class="flex-centered" style="width: 100%; height: 100%;">
          <img class="icon" src="../assets/icons/account.png" alt="">
        </div>
      </template>
    </Field>
    <Field
      v-model="password"
      type="password"
      name="password"
      placeholder="请输入密码"
      size="large"
      autocomplete="current-password"
      :rules="[{ required: true, message: '请填写密码' }]"
    >
      <template #left-icon>
        <div class="flex-centered" style="width: 100%; height: 100%;">
          <img class="icon" src="../assets/icons/password.png" alt="">
        </div>
      </template>
    </Field>
    <div class="submit-button-container">
      <Button round block size="large" type="primary" native-type="submit">
        登录
      </Button>
      <div style="display: flex;width: 100%;">
        <div @click="$emit('register')" class="go-to-register">注册账号</div>
      <div @click="$router.push('/reset-password')" class="go-to-register">找回密码</div>
      </div>
    </div>
  </Form>
</template>

<style lang="less" scoped>
.icon {
  width: 20px;
  height: 20px;
  margin-right: 20px;
}

.submit-button-container {
  margin-top: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.go-to-register {
  // display: inline;
  width: 50%;
  text-align: center;
  margin-top: 20px;
  font-size: 12px;
  color: #ccc;
  // border-bottom: 2px solid #ddd;
  padding-bottom: 2px;
}
</style>
